import { Action, createReducer, on } from '@ngrx/store';
import { addTodo, deleteTodo } from '../actions/todo.actions';
import { v4 as uuidv4 } from 'uuid'
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';


export const todoFeatureKey = 'todo';

export interface Todo {
  id: string
  title: string
}

// 继承 EntityState 数据类型
export interface State extends EntityState<Todo> {}

// 创建实体适配器对象
export const adapter: EntityAdapter<Todo> = createEntityAdapter<Todo>()

// 获取初始状态，可以传递参数也可能不传
// { ids: [], entities: {} }
export const initialState: State = adapter.getInitialState({ ids: [1], entities: { 1: {id: 1, title: '123'}} })

export const reducer = createReducer(
  initialState,
  // 使用提供的实例方法为 todos 添加一条数据，第一个参数为数据，第二个参数为添加的目标
  on(addTodo, (state, action) => adapter.addOne({
    id: uuidv4(),
    title: action.title
  }, state)),
  // 使用提供的实例方法删除 todos 一条数据，第一个参数为 id，第二个参数为删除目标
  on(deleteTodo, (state, action) => adapter.removeOne(action.id, state))
);

